var hplus = {
		ajaxError:function(xhr, ajaxOptions, thrownError){
			 layer.alert("<div>Http status: " + xhr.status + " " + xhr.statusText + "</div><div>ajaxOptions: " + ajaxOptions + "</div><div>thrownError: " + thrownError + "</div><div>" + xhr.responseText + "</div>",{icon:2});
		},
		ajaxDone: function(json) {
		    if (json["result"] == "error") {
		    	if (json["message"]) {
		    		layer.alert(json["message"],{icon:2});
		    	}
		    } else {
		    	if (json["result"] == "success") {
	                if (json["message"]) {
	                	parent.layer.msg(json["message"]);
	                }
	            }
		    }
		},
		jsonEval:function(data) {
			try{
				if ($.type(data) == 'string')
					return eval('(' + data + ')');
				else return data;
			} catch (e){
				return {};
			}
		}
};


(function($) {
	//扩展serializeJson
    $.fn.serializeJson=function(){  
        var serializeObj={};  
        $(this.serializeArray()).each(function(){  
            serializeObj[this.name]=this.value;  
        });  
        return serializeObj;  
    };  

    //扩展validator
	if ($.validator) {
		$.validator.addMethod("alphanumeric", function(value, element) {
			return this.optional(element) || /^\w+$/i.test(value);
		}, "Letters, numbers or underscores only please");
		
		$.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[a-z]+$/i.test(value);
		}, "Letters only please"); 
		
		$.validator.addMethod("phone", function(value, element) {
			return this.optional(element) || /^[0-9 \(\)]{7,30}$/.test(value);
		}, "Please specify a valid phone number");
		
		$.validator.addMethod("postcode", function(value, element) {
			return this.optional(element) || /^[0-9 A-Za-z]{5,20}$/.test(value);
		}, "Please specify a valid postcode");
		
		$.validator.addMethod("date", function(value, element) {
			value = value.replace(/\s+/g, "");
			if (String.prototype.parseDate){
				var $input = $(element);
				var pattern = $input.attr('dateFmt') || 'yyyy-MM-dd';
	
				return !$input.val() || $input.val().parseDate(pattern);
			} else {
				return this.optional(element) || value.match(/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/);
			}
		}, "Please enter a valid date.");
		
		$.validator.addClassRules({
			date: {date: true},
			alphanumeric: { alphanumeric: true },
			lettersonly: { lettersonly: true },
			phone: { phone: true },
			postcode: {postcode: true}
		});
		$.validator.setDefaults({errorElement:"span"});
		$.validator.autoCreateRanges = true;
	}
	$.fn.extend({
		initUI: function(){
			return this.each(function(){
				if($.isFunction(initUI)) initUI(this);
			});
		},
		ajaxUrl: function(op){
			var $this = $(this);
			$.ajax({
				type: op.type || 'GET',
				url: op.url,
				data: op.data,
				cache: false,
				success: function(response){
					var json = hplus.jsonEval(response);
					if (json["result"]=="error"){
						if (json["message"]) layer.alert(json["message"],{icon:2});
					} else {
						$this.html(response);
						if ($.isFunction(op.callback)) op.callback(response);
					}
					if (json["result"]=="timeout"){
						layer.alert(json["message"],{icon:2})
					} 
				},
				error: hplus.ajaxError,
				statusCode: {
					503: hplus.ajaxError
				}
			});
		},
		loadUrl: function(url,data,callback){
			$(this).ajaxUrl({url:url, data:data, callback:callback});
		},
		ajaxTodo:function(){
			return this.each(function(){
				var $this = $(this);
				$this.click(function(event){
					var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
					
					if (!url.isFinishedTm()) {
						layer.alert($this.attr("warn") || "请选择数据！",{icon:2});
						return false;
					}
					var title = $this.attr("title");
					if (title) {
						var confirmLayer = layer.confirm(title, {btn: ["确定","取消"]}, function(){
							layer.close(confirmLayer);
							ajaxTodo(url, $this.attr("callback"));
						}, function(){});
					} else {
						ajaxTodo(url, $this.attr("callback"));
					}
					event.preventDefault();
				});
			});
		},
		selectedTodo: function(){
			function _getIds(selectedIds, targetType){
				var ids = "";
				$("input:checked").filter("[name='"+selectedIds+"']").each(function(i){
					var val = $(this).val();
					ids += i==0 ? val : ","+val;
				});
				return ids;
			}
			return this.each(function(){
				var $this = $(this);
				var selectedIds = $this.attr("rel") || "ids";
				var postType = $this.attr("postType") || "map";
	
				$this.click(function(){
					var targetType = $this.attr("targetType");
					var ids = _getIds(selectedIds, targetType);
					if (!ids) {
						layer.alert($this.attr("warn") || "请选择数据！",{icon:2});
						return false;
					}
					
					var _callback = $this.attr("callback") || (targetType == "dialog" ? listDialogAjaxDone : listAjaxDone);
					if (! $.isFunction(_callback)) _callback = eval('(' + _callback + ')');
					
					function _doPost(){
						$.ajax({
							type:'POST', url:$this.attr('href'), dataType:'json', cache: false,
							data: function(){
								if (postType == 'map'){
									return $.map(ids.split(','), function(val, i) {
										return {name: selectedIds, value: val};
									});
								} else {
									var _data = {};
									_data[selectedIds] = ids;
									return _data;
								}
							}(),
							success: _callback,
							error: hplus.ajaxError
						});
					}
					var title = $this.attr("title");
					if (title) {
						var layer_confirm = layer.confirm(title, {btn: ["确定","取消"]}, function(){
							layer.close(layer_confirm);
							_doPost();
						}, function(){});
					} else {
						_doPost();
					}
					return false;
				});
				
			});
		}
	});
    $.extend(String.prototype, {
        isPositiveInteger: function() {
            return (new RegExp(/^[1-9]\d*$/).test(this));
        },
        isInteger: function() {
            return (new RegExp(/^\d+$/).test(this));
        },
        isNumber: function(value, element) {
            return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
        },
        trim: function() {
            return this.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
        },
        startsWith: function(pattern) {
            return this.indexOf(pattern) === 0;
        },
        endsWith: function(pattern) {
            var d = this.length - pattern.length;
            return d >= 0 && this.lastIndexOf(pattern) === d;
        },
        replaceSuffix: function(index) {
            return this.replace(/\[[0-9]+\]/, "[" + index + "]").replace("#index#", index);
        },
        trans: function() {
            return this.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"');
        },
        encodeTXT: function() {
            return (this).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll(" ", "&nbsp;");
        },
        replaceAll: function(os, ns) {
            return this.replace(new RegExp(os, "gm"), ns);
        },
        replaceTm: function($data) {
            if (!$data) {
                return this;
            }
            return this.replace(RegExp("({[A-Za-z_]+[A-Za-z0-9_]*})", "g"),
            function($1) {
                return $data[$1.replace(/[{}]+/g, "")];
            });
        },
        replaceTmById: function(_box) {
            var $parent = _box || $(document);
            return this.replace(RegExp("({[A-Za-z_]+[A-Za-z0-9_]*})", "g"),
            function($1) {
                var $input = $parent.find("#" + $1.replace(/[{}]+/g, ""));
                return $input.val() ? $input.val() : $1;
            });
        },
        isFinishedTm: function() {
            return ! (new RegExp("{[A-Za-z_]+[A-Za-z0-9_]*}").test(this));
        },
        skipChar: function(ch) {
            if (!this || this.length === 0) {
                return "";
            }
            if (this.charAt(0) === ch) {
                return this.substring(1).skipChar(ch);
            }
            return this;
        },
        isValidPwd: function() {
            return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this));
        },
        isValidMail: function() {
            return (new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()));
        },
        isSpaces: function() {
            for (var i = 0; i < this.length; i += 1) {
                var ch = this.charAt(i);
                if (ch != " " && ch != "\n" && ch != "\t" && ch != "\r") {
                    return false;
                }
            }
            return true;
        },
        isPhone: function() {
            return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
        },
        isUrl: function() {
            return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
        },
        isExternalUrl: function() {
            return this.isUrl() && this.indexOf("://" + document.domain) == -1;
        }
    });
})(jQuery);

$().ready(function() {
	initEnv();
});

/**
 * 带文件上传的ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 */
function iframeCallback(form, callback){
	var $form = $(form), $iframe = $("#callbackframe");
	if(!$form.valid()) {return false;}

	if ($iframe.size() == 0) {
		$iframe = $("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
	}
	if(!form.ajax) {
		$form.append('<input type="hidden" name="ajax" value="1" />');
	}
	form.target = "callbackframe";
	
	_iframeResponse($iframe[0], callback || ZT.ajaxDone);
}
function _iframeResponse(iframe, callback){
	var $iframe = $(iframe), $document = $(document);

	$document.trigger("ajaxStart");
	$iframe.bind("load", function(event){
		$iframe.unbind("load");

		$document.trigger("ajaxStop");
		if (iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For Safari
			iframe.src == "javascript:'<html></html>';") { // For FF, IE
			return;
		}

		var doc = iframe.contentDocument || iframe.document;

		// fixing Opera 9.26,10.00
		if (doc.readyState && doc.readyState != 'complete') return; 
		// fixing Opera 9.64
		if (doc.body && doc.body.innerHTML == "false") return;
	   
		var response;
		
		if (doc.XMLDocument) {
			// response is a xml document Internet Explorer property
			response = doc.XMLDocument;
		} else if (doc.body){
			try{
				response = $iframe.contents().find("body").text();
				response = jQuery.parseJSON(response);
			} catch (e){ // response is html document or plain text
				response = doc.body.innerHTML;
			}
		} else {
			// response is a xml document
			response = doc;
		}
		
		callback(response);
	});
}
function validateCallback(form, callback, confirmMsg) {
    var $form = $(form);
    if (!$form.valid()) {
        return false;
    }
    var _submitFn = function() {
        $form.find(":focus").blur();
        $.ajax({
            type: form.method || "POST",
            url: $form.attr("action"),
            data: $form.serializeArray(),
            dataType: "json",
        	async:false,
            cache: false,
            success: callback || hplus.ajaxDone,
            error: hplus.ajaxError
        });
    };
    if (confirmMsg) {
    	layer.confirm(confirmMsg, {btn: ["确定","取消"]}, function(){_submitFn();}, function(){});
    } else {
        _submitFn();
    }
    return false;
}
function initUI($p) {
	if ($.fn.selectedTodo) $("a[target=selectedTodo]", $p).selectedTodo();
	if ($.fn.ajaxTodo) $("a[target=ajaxTodo]", $p).ajaxTodo();
    if ($.fn.validate) {
        $("form.required-validate", $p).each(function() {
            var $form = $(this);
    		$form.find("input").each(function(){
    			var $this = $(this);
    			if($this.attr("name")&&typeof($this.attr("id"))=="undefined"){
    				$this.attr("id",$this.attr("name").replace(".","_"));
    			}
    		});
            $form.validate({
                onsubmit: false,
                focusInvalid: false,
                focusCleanup: true,
                ignore: ".ignore"
            });
        })
    }
	if ($.fn.select2){
		$("form .select2Input", $p).each(function(){
			$(this).select2(); 
		});
	}
	//需bootstrapTable插件支持
	if ($.fn.bootstrapTable){
		$("#bootstrapTable", $p).each(function(){
			var $table = $(this);
			$table.bootstrapTable({
				striped:true,
				height:$(window).height(),
				pagination:true,
				sidePagination:"server",
				cache:false,
				pageSize:20,
				pageList:[10, 20, 50, 100, 200, 500,1000],
				toolbar:"#toolbar",
				showColumns:true,
				showRefresh:true,
				iconSize:"outline",
				queryParamsType:"long",
				queryParams:function(params){
					if($("#AdvanceSearch").size()>0) {
			            $.each($("#AdvanceSearch form").serializeJson(),function(index,item){
			            	params[index] = item;
			            });
					}
					params["is_ajax"]="T";
					return params;
				}
			});
			$(window).resize(function () {
				$table.bootstrapTable('resetView', {
					height: $(window).height()
		      });
		    });
		});
	}
}
var loadLayer;
function initEnv() {
    $(document).ajaxStart(function() {
    	loadLayer = layer.load(0, {shade: false});
    }).ajaxStop(function() {
    	layer.close(loadLayer);
    });
	
	setTimeout(function() {
		$(document).initUI();
	},10);
}
function listDialogAjaxDone(json){
	hplus.ajaxDone(json);
	if (json["result"] == "success"){
		parent.thisBootstrapTableRefresh();
		parent.layer.msg(json.message);
		var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
		parent.layer.close(index);
	}
}

function listAjaxDone(json){
	hplus.ajaxDone(json);
	if (json["result"] == "success"){
		thisBootstrapTableRefresh();
	}
}
//bootstrapTable插件扩展函数
function xuhaoFormatter(value,row,index){
	var options = $('#bootstrapTable').bootstrapTable('getOptions');
	var page = options.pageNumber;
	var pagesize = options.pageSize;
	return (page-1)*pagesize+index+1;
}
function imageShowFormatter(value,row,index){
	return "<img style='height:50px' src='"+row.image+"'/>";
}
function imageLinkFormatter(value,row,index){
	return "<a href='"+row.image+"' target='_blank'>查看图片</a>";
}
function fileLinkFormatter(value,row,index){
	return "<a href='"+row.upload+"' target='_blank'>下载附件</a>";
}
function enableFlagFormatter(value,row,index){
	if(row.enable_flag=="T"){
		return "<span style='color:green'>可用</span>";
	}else {
		return "<span style='color:red'>禁用</span>";
	}
}
function timeToDateFormatter(value,row,index){
	if(value){
		return value.substring(0,10);
	}
}
function bootstrapTableRefresh(){
	var params = $("#AdvanceSearch form").serializeJson();
	params["pageNumber"] = 1;
	$("#bootstrapTable").bootstrapTable("refresh",{query:params});
	return false;
}
function thisBootstrapTableRefresh(){
	$("#bootstrapTable").bootstrapTable("refresh");
}

function ajaxTodo(url, callback){
	var $callback = callback || hplus.ajaxDone;
	if (! $.isFunction($callback)) $callback = eval('(' + callback + ')');
	$.ajax({
		type:'POST',
		url:url,
		dataType:"json",
		cache: false,
		success: $callback,
		error: hplus.ajaxError
	});
}

function ajaxTodoByConfirm(url,confirm,callback){	
	var confirmLayer = layer.confirm(confirm, {btn: ['确定','取消']}, function(){layer.close(confirmLayer);ajaxTodo(url, callback);}, function(){});
}
function changeURLArg(url,arg,arg_val){ 
    var pattern=arg+'=([^&]*)'; 
    var replaceText=arg+'='+arg_val; 
    if(url.match(pattern)){ 
        var tmp='/('+ arg+'=)([^&]*)/gi'; 
        tmp=url.replace(eval(tmp),replaceText); 
        return tmp; 
    }else{ 
        if(url.match('[\?]')){ 
            return url+'&'+replaceText; 
        }else{ 
            return url+'?'+replaceText; 
        } 
    } 
    return url+'\n'+arg+'\n'+arg_val; 
} 